﻿using System.IO;
using System.Text;

namespace UFrame.NetSocket
{
    public abstract class JsonSerialiser : IPacketSerialiser
    {
        public T Deserialise<T>(byte[] packetBytes, int offset, int length)
        {
            throw new System.NotImplementedException();
        }

        public byte[] Serialize<T>(T packet)
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var binaryWriter = new BinaryWriter(memoryStream))
                {
                    var nameBytes = Encoding.ASCII.GetBytes(typeof(T).Name);
                    var jsonText = UnityEngine.JsonUtility.ToJson(packet);
                    var serialised = System.Text.Encoding.UTF8.GetBytes(jsonText);
                    binaryWriter.Write(nameBytes.Length);
                    binaryWriter.Write(serialised.Length);
                    binaryWriter.Write(nameBytes);
                    binaryWriter.Write(serialised);
                }

                var packetBytes = memoryStream.ToArray();
                return packetBytes;
            }
        }
    }
}